package com.kqb.common.domain;

import com.kqb.common.exception.BusinessException;
import com.kqb.common.exception.ValidateException;
import com.kqb.common.exception.base.BaseException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杉果树皮
 * @date 2025/2/15 10:27
 * @description: 通用异常结果
 */
public class ErrorResult {

    /**
     * 验证异常
     *
     * @param result
     */
    public static void validate(BindingResult result) {
        //获取验证结果
        List<FieldError> errors = result.getFieldErrors();
        if (null != errors && errors.size() > 0) {
            Map<String, String> errorMap = new HashMap<>();
            //验证未通过  遍历错误信息
            errors.forEach(el -> {
                errorMap.put(el.getField(), el.getDefaultMessage());//将错误字段与消息提示  对应保存起来
            });
            //有错误信息 抛出错误信息
            throw new ValidateException(errorMap);
        }
    }


    /**
     * 业务异常
     *
     * @param result
     */
    public static void business(int result, String module, String defaultMessage) {
        if (result == 0) {
            throw new BusinessException(module, defaultMessage);
        }
    }

}
